<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域-- -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <!-- 输入框区域 -->
            <el-input placeholder="请输入内容" v-model="queryInfo.query" @blur='blurInput' clearable @clear='blurInput'>
                <el-button slot="append" icon="el-icon-search" @click='getUsers()' ></el-button>
            </el-input>
                </el-col>
                <!-- 用户添加区域 -->
                <el-col :span="4">
                    <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 用户数据表格 -->
          <el-table :data="UsersList" stripe style="width: 100%" border>
            <el-table-column  label="序号" type='index' width="50"></el-table-column>
            <el-table-column prop="username" label="姓名" width="180"></el-table-column>
            <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
            <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
            <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
            <el-table-column prop="mg_state" label="状态" width="180">
                <!-- 状态 -->
                <template slot-scope="scopes">
                    <el-switch v-model="scopes.row.mg_state" @change='changeState(scopes.row.mg_state,scopes.row.id)' active-color="#13ce66" inactive-color="#ff4949" ></el-switch>
                </template>
            </el-table-column>
            <el-table-column  label="操作" width="180">
                <!-- 操作按钮 -->
                <template slot-scope="scopes">
                <el-row>
                    <el-tooltip effect="dark" content="修改用户" placement="top" :enterable='false'>
                    <!-- 修改用户 -->
                        <el-button type="primary" size='mini' icon="el-icon-edit" @click='checkEditUser(scopes.row.id)'></el-button>
                    </el-tooltip>
                    <!-- 删除用户 -->
                    <el-tooltip effect="dark" content="删除用户" placement="top" :enterable='false'>
                        <el-button type="danger" size='mini' icon="el-icon-delete" @click='toDelete(scopes.row.id)'></el-button>
                    </el-tooltip>
                    <!-- 分配用户 -->
                    <el-tooltip effect="dark" content="角色分配" placement="top" :enterable='false'>
                        <el-button type="warning" size='mini' icon="el-icon-setting" @click='toSetting(scopes.row)'></el-button>
                    </el-tooltip>
                </el-row>
                </template>
            </el-table-column>
          </el-table>
           <!-- 分页详情 -->
          <div class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryInfo.pegenum" :page-sizes="[1, 2, 5, 8]" :pager-count="5"
             :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>
        </el-card>
          <!-- 添加用户模态框 -->
            <el-dialog title="添加用户" :visible.sync="dialogVisible"
                width="30%" @close='resetForm("addFormRef")'
                >
                <el-form :model="addUserForm" :rules='rules' ref='addFormRef'  label-width="80px">
                    <el-form-item label="用户名称" prop="username">
                        <el-input v-model="addUserForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="用户密码" prop="password">
                        <el-input v-model="addUserForm.password" style="password"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="addUserForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                        <el-input v-model="addUserForm.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="checkUser">添 加</el-button>
                </span>
            </el-dialog>
            <!-- 修改用户模态框 -->
            <el-dialog title="修改用户" :visible.sync="editVisible"
                width="30%" @close='resetForm("editFormRef")'
                >
                <el-form :model="editUserForm" :rules='editRules' ref='editFormRef' label-width="80px">
                    <el-form-item label="用户名称" prop="username">
                        <el-input v-model="editUserForm.username" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="editUserForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                        <el-input v-model="editUserForm.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                        <el-button @click="editVisible = false">取 消</el-button>
                        <el-button type="primary" @click="checkEdit">修 改</el-button>
                </span>
            </el-dialog>
          <!-- 角色分配模态框 -->
          <el-dialog title="角色分配" :visible.sync="userRoleVisible" @close='resetForm("selectRoleFormRef")'>
              <div>
                <p>当前用户: {{userRole.username}}</p>
                <p>当前角色: {{userRole.role_name}}</p>
              </div>
              <el-form ref='selectRoleFormRef'>
                <el-form-item label="分配新角色" >
                  <el-select v-model="roleNameId" placeholder="请选择" >
                    <el-option :label="item.roleName" :value='item.id'  v-for='item in rolesArry' :key='item.id'></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="userRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click='allotUserRole'>确 定</el-button>
              </div>
          </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    var checkEmail = (rule, value, callback) => {
      const EmailReg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
      if (EmailReg.test(value)) {
        //   校验成功
        return callback()
      } else {
        return callback(new Error('邮箱验证失败'))
      }
    }
    var checkMobile = (rule, value, callback) => {
      const EmailReg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (EmailReg.test(value)) {
        //   校验成功
        return callback()
      } else {
        return callback(new Error('手机号码格式不正确'))
      }
    }
    return {
      queryInfo: {
        // 参数
        query: '',
        // 当前页
        pagenum: 1,
        // 一页显示的条数
        pagesize: 2
      },
      UsersList: [],
      rolesArry: [],
      total: 0,
      dialogVisible: false,
      editVisible: false,
      userRoleVisible: false,
      // 选中的角色id
      roleNameId: '',
      // 用户id
      userId: 0,
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editUserForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      userRole: {},
      // 修改用户规则
      editRules: {
        email: [
          { required: false, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur'] }

        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }

        ]
      },
      //   添加用户在return当中作为数据的一种---切记不可错
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 5, max: 8, message: '长度在 5 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: false, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur'] }

        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }

        ]

      }
    }
  },
  methods: {
    // 获取用户列表数据函数
    async getUsers () {
      const data = await this.$http.get('users', { params: this.queryInfo })
      if (data.meta.status === 200) {
        this.UsersList = data.data.users
        this.total = data.data.total
      } else {
        return false
      }
    },
    // 鼠标离开输入框查询用户
    blurInput () {
      if (this.queryInfo.query.length === 0) {
        this.getUsers()
      }
    },
    async checkEditUser (id) {
    // 查询用户
      this.editVisible = true
      const data = await this.$http.get('users/' + id)
      // 数据重新赋值
      this.editUserForm.id = data.data.id
      this.editUserForm.username = data.data.username
      this.editUserForm.email = data.data.email
      this.editUserForm.mobile = data.data.mobile
    },
    toDelete (id) {
    // 删除用户
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.$http.delete('users/' + id)
        this.getUsers()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async toSetting (userRole) {
    // 角色分配
      this.userId = userRole.id
      this.userRoleVisible = true
      this.userRole = userRole
      // 获取所有角色列表
      const data = await this.$http.get('roles')
      if (data.meta.status !== 200) {
        return this.$message.success('获取角色失败')
      } else {
        this.rolesArry = data.data
      }
    },
    // 添加用户校验表单
    checkUser () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$Message.error('信息输入错误，请重新输入正确格式')
        } else {
        // 发送添加用户信息请求
          const data = await this.$http.post('users', this.addUserForm)
          if (data.meta.status === 201) {
            this.$message.success('创建用户成功')
            this.dialogVisible = false
            this.getUsers()
          } else {
            this.$Message.error('创建用户失败')
          }
        }
      })
    },
    // 修改用户校验
    checkEdit () {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$Message.error('信息输入错误，请重新输入正确格式')
        } else {
        // 发送添加用户信息请求
          const data = await this.$http.put('users/' + this.editUserForm.id, this.editUserForm)
          if (data.meta.status === 200) {
            this.$message.success('修改用户成功')
            this.editVisible = false
            this.getUsers()
          } else {
            this.$Message.error('修改用户失败')
          }
        }
      })
    },
    // 重置表单
    resetForm (val) {
      this.$refs[val].resetFields()
    },
    handleSizeChange (val) {
    // 改变单页显示的条数
      this.queryInfo.pagesize = val
      // 重新发送请求
      this.getUsers()
    },
    handleCurrentChange (val) {
    // 改变当前页
      this.queryInfo.pagenum = val
      this.getUsers()
    },
    async changeState (state, id) {
    // 发送axios请求改变用户状态
      const data = await this.$http.put('users/' + id + '/state/' + state)
      if (data.meta.status !== 200) {
        //   将已经更改的状态值还原回去
        state = !state
        return this.$Message.error('更新用户状态失败')
      } else {
        this.$Message.success('更新状态成功')
      }
    },
    // 分配用户角色
    async allotUserRole () {
      const data = await this.$http.put(`users/${this.userId}/role`, {
        rid: this.roleNameId
      })
      if (data.meta.status !== 200) return this.$message.error('角色分配失败')
      this.$message.success('角色分配成功')
      this.userRoleVisible = false
      // 重新获取数据
      this.getUsers()
    }
  },
  created: function () {
    //   调用获取用户列表函数获取用户信息
    this.getUsers()
  }
}
</script>

<style lang="less" scoped>

</style>
